package com.lcz.lcz_blog.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcz.lcz_blog.entity.Blog;
import com.lcz.lcz_blog.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.apache.ibatis.type.JdbcType;
import org.apache.tomcat.util.buf.UEncoder;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author 刘传政
 * @since 2022-01-17
 */
public interface BlogMapper extends BaseMapper<Blog> {

    /**
     * 一对一关联查询
     */

    @Results(id = "blogResultMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "user", column = "user_id", one = @One(select = "com.lcz.lcz_blog.mapper.BlogMapper.queryUserById")),
            @Result(property = "collectCount", column = "id", one = @One(select = "com.lcz.lcz_blog.mapper.BlogMapper.queryCollectCount"))
    })
    @Select("SELECT * FROM tb_blog WHERE id = #{id}")
    Blog queryBlogById(@Param("id") int id);

    @Select("SELECT id,username,phone,icon_url FROM tb_user WHERE id = #{id}")
    User queryUserById(@Param("id") int userId);

    @Select("SELECT count(*) FROM `tb_collect_tblog_tuser` t WHERE t.blog_id = #{blog_id}")
    Integer queryCollectCount(@Param("blog_id") int blog_id);

    @Select("SELECT count(*) FROM `tb_collect_tblog_tuser` t WHERE t.blog_id = #{blog_id} AND t.user_id = #{user_id}")
    Integer myCollectedCount(@Param("blog_id") int blog_id, @Param("user_id") int user_id);

    /**
     * 一对一关联查询列表
     */
    @ResultMap(value = "blogResultMap")
    @Select("SELECT * FROM tb_blog")
    List<Blog> queryAll();


    /**
     * 分页查询,并增加筛选条件
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    @ResultMap(value = "blogResultMap")
    @Select("select * from tb_blog ${ew.customSqlSegment}")
    IPage<Blog> queryPage(Page<Blog> page, @Param("ew") QueryWrapper<Blog> queryWrapper);
    //SELECT	* FROM	tb_blog b WHERE	b.id IN ( SELECT c.blog_id FROM tb_collect_tblog_tuser c WHERE c.user_id = 3 ) ORDER BY update_time DESC
    @ResultMap(value = "blogResultMap")
    @Select("SELECT * FROM tb_blog b WHERE b.id IN ( SELECT c.blog_id FROM tb_collect_tblog_tuser c WHERE c.user_id = ${userId} ) ${ew.customSqlSegment}")
    IPage<Blog> queryCollectPage(Page<Blog> page, @Param("ew") QueryWrapper<Blog> queryWrapper,@Param("userId") int userId);
}
